package com.tmall.testgen.common.util;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;



/**
 * @author haojia
 * @date 2014-07-04
 */
public class VMUtil {

    
    private static URLClassLoader classLoader;
	
    public static void main(String[] args) throws Exception {
    	
    	getLocalVMs();
	}
    
    private static String  findToolsPath(){
    	String javaHome=System.getProperty("java.home");
        if(javaHome.endsWith("jre")){
            javaHome=javaHome.substring(0, javaHome.length()-3);
        }
        if((!javaHome.endsWith("/"))&&(!javaHome.equals("\\")))
        	javaHome=javaHome+"/";
        
        String path=javaHome+"lib/tools.jar";
        
        if(new File(path).exists())
        	return path;
        
       
        File pp= new File(javaHome).getParentFile();
        for(String f:pp.list()){
        	if(f.contains("jdk"))
        		return pp.getAbsolutePath()+"/"+f+"/lib/tools.jar";
        }
       return null;
    }
    private static URLClassLoader getClassLoader() throws Exception{
        
        if(classLoader==null){
           
            URL[] urls=new URL[1];
            urls[0]=new File(findToolsPath()).toURL();
            System.out.println(urls[0]);
            classLoader=new URLClassLoader(urls);
        }
        return classLoader;
    }
    
   
	public static void attatch(String pid,String jarPath) throws Exception{
		
		if(isWindows()&&(jarPath.startsWith("/")||jarPath.startsWith("\\"))){
			jarPath=jarPath.substring(1);
		}
		System.out.println("jarPath:"+jarPath);
	    Class virtualMachineClass=Class.forName("com.sun.tools.attach.VirtualMachine",true,getClassLoader());
	    Method attachMethod=virtualMachineClass.getMethod("attach", String.class);
	    Object virtualMachineObj=attachMethod.invoke(virtualMachineClass, pid);
	    
	   
	    Method loadAgentMethod=virtualMachineObj.getClass().getMethod("loadAgent", String.class);
	    loadAgentMethod.invoke(virtualMachineObj, jarPath);
	    
        
		Thread.sleep(3000);
		Method detachMethod=virtualMachineObj.getClass().getMethod("detach");
        detachMethod.invoke(virtualMachineObj);
		
	}
	
	
	public static Map<String,String> getLocalVMs() throws Exception{
	    
	   
	    
		Map<String,String> result=new HashMap<String,String>();
		Class virtualMachineClass=Class.forName("com.sun.tools.attach.VirtualMachine",true,getClassLoader());
		Method machineListMethod=virtualMachineClass.getMethod("list");
		Object machineListObj=machineListMethod.invoke("virtualMachineClass");
		
		if(machineListObj!=null&&machineListObj instanceof List){
		    List machineList=(List) machineListObj;
		    for(int i=0;i<machineList.size();i++){
		        Method displayNameMethod=machineList.get(i).getClass().getMethod("displayName");
		        String disName=(String) displayNameMethod.invoke(machineList.get(i));
		        
		        Method idMethod=machineList.get(i).getClass().getMethod("id");
                String id=(String) idMethod.invoke(machineList.get(i));
                
                
		        int pos=disName.indexOf(" ");
	            result.put(id,disName.substring(0,pos>0?pos:disName.length()));
		    }
		}
		System.out.println("返回虚拟机列表:"+result);
		return result;
	}
	
	 private static boolean isWindows(){
	        Properties props=System.getProperties();
	        String osName=props.getProperty("os.name");
	        if(osName.toLowerCase().contains("windows"))
	            return true;
	        
	        return false;
	    } 
}
